package app.service

import app.util.Config
import app.util.DB
import org.jooq.*
import org.jooq.impl.DSL

open class CommonService {
    var error = ""      // 错误信息

    val config = Config.getInstance()
    val prefix = config.getProperty("db.prefix").toString()
    val configuration = DB.getInstance(config)
    val create = getDSLContext(configuration)

    /**
     * 获取DSLContext对象
     * @return DSLContext
     */
    fun getDSLContext(configuration: Configuration): DSLContext {
        val dslContext = DSL.using(configuration)
        return dslContext
    }

    /**
     * 获取表名
     * @param table
     * @param table_prefix
     * @return boolean
     */
    fun dslTable(table: String, table_prefix: String = prefix): Table<Record> {
        return DSL.table(table_prefix + table)
    }

    /**
     * 删除数据
     * @param table
     * @param id
     * @param key
     * @return boolean
     */
    fun dslDelete(table: String, id: Int, key: String? = null): Boolean {
        var primary_key = "id"
        if (key != null) primary_key = key
        val fetch = create.delete(this.dslTable(table)).where(DSL.field(primary_key).eq(id)).execute()
        if (fetch == 0) return false
        return true
    }

    /**
     * 获取上一条插入语句的主键值
     * @return Any
     */
    fun last_insert_id(): Any {
        val fetch = create.fetch("select last_insert_id() as id")
        val id = fetch.getValue(0,"id")
        return id
    }
}